//
//  JXForumController.m
//  JiaoX
//
//  Created by jiaoxiu－005 on 15/1/4.
//  Copyright (c) 2015年 北京娇羞科技有限公司. All rights reserved.
//

#import "JXForumController.h"
#import "JXPopMenu.h"
#import "PopMenuListView.h"
#import "JXReplyMineCtl.h"
#import "PopMenuBean.h"
#import "JXMinePostsCtl.h"
#import "JXPostsDetailCtl.h"
#import "JXNewTopicCtl.h"
#import "ForumDataTool.h"
#import "ForumHomeCell.h"
#import "SGFocusImageItem.h"
#import "SGFocusImageFrame.h"
#import "MJRefresh.h"
#import "JXChatListCtl.h"
#import "JXChatManager.h"
#import "JXTabBarController.h"
#import "JXPostsListCtl.h"

@interface JXForumController ()<JXPopMenuDelegate,PopMenuListViewDelegate,SGFocusImageFrameDelegate>

@property (nonatomic,strong) JXPopMenu *menu;
@property (nonatomic,strong) SGFocusImageFrame *bannerView;
@property (nonatomic,strong) NSMutableArray *itemArray;
@property (nonatomic,strong) NSMutableArray *bannerArray;
@property (nonatomic,strong) NSMutableArray *popMenuArray;



@end

@implementation JXForumController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"论坛";
    
    //设置顶部左右的按钮
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImageName:@"navigationbar_mine" highImageName:@"navigationbar_mine_highlighted" target:self action:@selector(showDialog)];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImageName:@"navigationbar_publish" highImageName:@"navigationbar_publish_highlighted" target:self action:@selector(sendPosts)];
    
    //初始化集合
    self.itemArray = [NSMutableArray array]; self.bannerArray = [NSMutableArray array];
    [self.tableView setTableFooterView:[[UIView alloc]init]];
    [self.tableView setSeparatorColor:JXColor(242, 242, 242)];
    [self.tableView addHeaderWithTarget:self action:@selector(requestData)];
    [self.tableView headerBeginRefreshing];
}

#pragma mark 数据请求与操作
-(void)requestData{
    [ForumDataTool getHomeDataWithModelId:@"" pageIndex:0 lastId:@"" modulePostsType:0 success:^(BBSHomeData *result) {
        [Utils refreshComplete:self.tableView];
        if ([Utils isBlankString:result.data]) {
            //论坛列表
            [self.itemArray removeAllObjects];
            [self.itemArray addObjectsFromArray:result.modelList];
            //顶部banner
            [self.bannerArray removeAllObjects];
            [self.bannerArray addObjectsFromArray:result.bannerList];
            [self setBannerData];
            
            [self.tableView reloadData];
        }else{
            [DialogUtils showTipsWithView:self.navigationController.view String:result.data];
        }
    } failure:^(NSError *error) {
        [Utils refreshComplete:self.tableView];
        [DialogUtils showTipsWithView:self.navigationController.view String:@"加载失败"];
    }];
}


-(void)setBannerData{
    self.tableView.tableHeaderView = nil;
    if(!_bannerArray.count)return;
    
    NSMutableArray *itemArray = [NSMutableArray arrayWithCapacity:_bannerArray.count+2];
    
    for (int i = 0; i < _bannerArray.count; i++)
    {
        HomeBanner *banner = _bannerArray[i];
        SGFocusImageItem *item = [[SGFocusImageItem alloc] initWithTitle:banner.url image:banner.bannerImg tag:i];
        [itemArray addObject:item];
    }
    
    if(_bannerArray.count>1){
        HomeBanner *startBanner = _bannerArray[_bannerArray.count-1];
        SGFocusImageItem *startItem = [[SGFocusImageItem alloc] initWithTitle:startBanner.url image:startBanner.bannerImg tag:_bannerArray.count-1];
        [itemArray insertObject:startItem atIndex:0];
        
        HomeBanner *endBanner = _bannerArray[0];
        SGFocusImageItem *endItem = [[SGFocusImageItem alloc] initWithTitle:endBanner.url image:endBanner.bannerImg tag:_bannerArray.count-1];
        [itemArray addObject:endItem];
    }
    
    SGFocusImageFrame *bannerView = [[SGFocusImageFrame alloc] initWithFrame:CGRectMake(0, 0, JXScreenW, JXScreenW*0.5) delegate:self imageItems:itemArray isAuto:NO];
    [bannerView scrollToIndex:0];
    [bannerView setDelegate:self];
    self.tableView.tableHeaderView = bannerView;
    _bannerView = bannerView;
}


#pragma mark - tableview 代理方法
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ForumHomeCell *cell = [ForumHomeCell cellWithTableView:tableView];
    [cell setBBSMode:self.itemArray[indexPath.row]];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    JXPostsListCtl *ctrl = [[JXPostsListCtl alloc]initWithBBSmodel:self.itemArray[indexPath.row] modelList:self.itemArray];
    [self.navigationController pushViewController:ctrl animated:NO];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.itemArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return FORUMHOMECELL_HEIGHT;
}

#pragma mark - SGFocusImageFrameDelegate
- (void)foucusImageFrame:(SGFocusImageFrame *)imageFrame didSelectItem:(SGFocusImageItem *)item{
    [Utils dealUrlWithController:self url:item.title title:@"" fromWebView:false];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[JXChatManager sharedInstance] openSession];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateBadgeNum) name:NOTI_UPDATA_BADGE_NUM object:nil];
    [(JXTabBarController *)self.tabBarController getUnreadCount];
    [self resetLeftItem];
    
    if (TOKEN) {
        //请求是否弹出第1次进入加10经验的dialog
        [ForumDataTool getforumSupPoint:^(Integral *result) {
            if (result.code==0) {
                if (result.integral==1) {
                    [DialogUtils showTipsWithView:self.navigationController.view String:@"今日登陆奖励\n经验值+10"];
                }
            }
        } failure:^(NSError *error) {
            
        }];
    }
    
}

-(void)resetLeftItem{
    UIButton *btn = (UIButton *)self.navigationItem.leftBarButtonItem.customView;
    if ([self.tabBarItem.badgeValue integerValue]) {
        [btn setBackgroundImage:[UIImage imageNamed:@"navigationbar_mine_red"] forState:UIControlStateNormal];
        [btn setBackgroundImage:[UIImage imageNamed:@"navigationbar_mine_red_highlighted"] forState:UIControlStateHighlighted];
    }else{
        [btn setBackgroundImage:[UIImage imageNamed:@"navigationbar_mine"] forState:UIControlStateNormal];
        [btn setBackgroundImage:[UIImage imageNamed:@"navigationbar_mine_highlighted"] forState:UIControlStateHighlighted];
    }
    // 设置按钮的尺寸为背景图片的尺寸
    btn.size = btn.currentBackgroundImage.size;
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    if (self.menu) {
        [self.menu dismiss];
        self.menu = nil;
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NOTI_UPDATA_BADGE_NUM object:nil];
}

-(NSInteger)updateBadgeNum{
    NSInteger result = 0;
    if (self.menu) {
        PopMenuBean *bean1 = [_popMenuArray firstObject];
        if (TOKEN) {
            bean1.bageNum = [UserDefaultsHelper integerForKey:KEY_MYPOSTS_NOTI_NUM];
            result +=bean1.bageNum;
        }
        PopMenuBean *bean2 = _popMenuArray[1];
        bean2.bageNum = [UserDefaultsHelper integerForKey:KEY_REPLY_MINE_COMT_NOTI_NUM]+[UserDefaultsHelper integerForKey:KEY_REPLY_MINE_COMT_NOTI_NUM];
        result +=bean2.bageNum;
        
        PopMenuBean *bean3 = [_popMenuArray lastObject];
        bean3.bageNum = [[JXChatManager sharedInstance].chatMsgDao getAllUnReadMsgCount];
        result +=bean3.bageNum;
        [self.menu updateView];
    }
    [self resetLeftItem];
    return result;
}

-(void)newMessageCome{
    [[NSNotificationCenter defaultCenter] postNotificationName:NOTI_UPDATA_BADGE_NUM object:nil];
}

#pragma mark - 私有方法

-(void)showDialog{
    
    _popMenuArray = [NSMutableArray array];

    if (TOKEN) {
        [_popMenuArray addObject:[[PopMenuBean alloc] initWithTitle:[UserDefaultsHelper stringForKey:KEY_NICK_NAME] bageNum:[UserDefaultsHelper integerForKey:KEY_MYPOSTS_NOTI_NUM] icon:[UserDefaultsHelper stringForKey:KEY_USER_IMG]]];
    }else{
        [_popMenuArray addObject:[[PopMenuBean alloc] initWithTitle:@"未登录" icon:@"ic_launcher"]];
    }
    [_popMenuArray addObject:[[PopMenuBean alloc] initWithTitle:@"回复我的" bageNum:[UserDefaultsHelper integerForKey:KEY_REPLY_MINE_COMT_NOTI_NUM]+[UserDefaultsHelper integerForKey:KEY_REPLY_MINE_POST_NOTI_NUM] icon:@"ic_menu_reply"]];
    [_popMenuArray addObject:[[PopMenuBean alloc] initWithTitle:@"私信聊天" bageNum:[[JXChatManager sharedInstance].chatMsgDao getAllUnReadMsgCount] icon:@"ic_menu_msg"]];
    
    PopMenuListView *listView = [[PopMenuListView alloc]initWithItemArray:_popMenuArray];
    listView.delegate = self;
    self.menu = [JXPopMenu popMenuWithContentView:listView];
    
    self.menu.delegate = self;
    self.menu.dimBackground = YES;
    [self.menu showInRect:CGRectMake(8, NavHeight-3, listView.width, listView.height)];
}

-(void)popMenuItemClick:(NSUInteger)index{
    if (self.menu) {
        [self.menu dismiss];
        self.menu = nil;
    }
    switch (index) {
        case 0:{
            //点击了我的帖子
            JXMinePostsCtl *ctrl = [[JXMinePostsCtl alloc]initWithModelList:self.itemArray];
            [self.navigationController pushViewController:ctrl animated:YES];
            break;
        }
        case 1:{
            //点击了回复我的
            JXReplyMineCtl *ctrl = [[JXReplyMineCtl alloc]init];
            [self.navigationController pushViewController:ctrl animated:YES];
            break;
        }
        case 2:{
            //点击了私信聊天
            JXChatListCtl *ctrl = [[JXChatListCtl alloc]init];
            [self.navigationController pushViewController:ctrl animated:YES];
            break;
            
        }
    }
}
-(void)sendPosts{
    JXNewTopicCtl* ctl =  [[JXNewTopicCtl alloc]initWithModelList:self.itemArray];
    [self.navigationController pushViewController:ctl animated:YES];
}
@end
